package com.hinnotek.amoeba.ui.activity.old

import android.app.Activity
import android.content.Intent
import android.os.Bundle
import android.view.View
import androidx.activity.viewModels
import com.lee.common.base.BaseActivity
import com.hinnotek.amoeba.R
import com.hinnotek.amoeba.base.BaseBean
import com.hinnotek.amoeba.bean.old.AmeobaCustomerListBean
import com.hinnotek.amoeba.bean.old.AmibaProjectListBean
import com.hinnotek.amoeba.bean.old.SellPurchaseRequistionDetailBean
import com.hinnotek.amoeba.databinding.ActivitySellPurchaseRequisitionAddBinding
import com.hinnotek.amoeba.dialog.CustomDialog
import com.hinnotek.amoeba.ext.initAdapter
import com.hinnotek.amoeba.utilities.*
import com.hinnotek.amoeba.viewmodels.AmibaViewModel
import com.hinnotek.amoeba.viewmodels.PublicInterfaceViewModel
import com.lee.common.network.getRequestBody
import com.lee.common.network.net.ObserverState
import com.lee.common.utils.SharedPreUtils
import com.xuexiang.xutil.common.StringUtils
import dagger.hilt.android.AndroidEntryPoint

@AndroidEntryPoint
class SellPurchaseRequisitionModifyActivity :
    BaseActivity<ActivitySellPurchaseRequisitionAddBinding>(), View.OnClickListener {

    private var purchaseTypeTo: String? = null
    private var amibaPurchaseId = 0
    private var customerId = 0
    private var amibaCustomerProjectId = 0
    private var amibaProjectId = 0
    private var provideProjectName: String = ""
    private var sellPurchaseRequistionDetailBean: SellPurchaseRequistionDetailBean? = null

    private val viewModel by viewModels<PublicInterfaceViewModel>()
    private val amibaViewModel by viewModels<AmibaViewModel>()


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_sell_purchase_requisition_add)
        setLeftVisible(true)
        setTitle("添加采购申请")

        setRightText("项目需料")?.setOnClickListener {
            val bundle = Bundle()
            bundle.putSerializable("detail", sellPurchaseRequistionDetailBean)
            IntentUtils.startActivity(mContext, SellProjectRequirementsAddActivity::class.java, bundle)
        }
    }

    override fun initVew() {
        bindingView.etDeliveryDate.setOnClickListener(this)
        bindingView.superButtonSubmit.setOnClickListener(this)
    }

    override fun onResume() {
        super.onResume()
        getAmibaPurchaseById(amibaPurchaseId)
    }

    override fun setData() {
        bindingView.superButtonSubmit.setText("修改采购单")
        purchaseTypeTo = intent.getStringExtra("purchase_type_to")
        amibaPurchaseId = intent.getIntExtra("amibaPurchaseId", -1)
        if (purchaseTypeTo == "market" || purchaseTypeTo == "technology") {
            //请求
            viewModel.getAmibaCustomerListByOrgId(SharedPreUtils.getInteger("orgId", 0))
                .observe(this,
                    object : ObserverState<MutableList<AmeobaCustomerListBean>>() {
                        override fun onDataChange(data: MutableList<AmeobaCustomerListBean>) {
                            val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                                for (index in data.indices) {
                                    this[index] = data[index].customerName
                                }
                            }
                            bindingView.escRelatedProject.initAdapter(arrayOfStrings)
                            bindingView.escRelatedProject.setOnItemClickListener { parent, view, position, id ->
                                amibaCustomerProjectId = data[position].customerId
                            }
                            super.onDataChange(data)
                        }
                    })

        } else if (purchaseTypeTo == "rD") {
            bindingView.llChooseUser.visibility = View.GONE
            //请求
            viewModel.getAmibaProjectListByOrgId(SharedPreUtils.getInteger("orgId", 0))
                .observe(this,
                    object : ObserverState<MutableList<AmibaProjectListBean>>() {
                        override fun onDataChange(data: MutableList<AmibaProjectListBean>) {
                            val arrayOfStrings = arrayOfNulls<String>(data.size).apply {
                                for (index in data.indices) {
                                    this[index] = data[index].projectName
                                }
                            }
                            bindingView.escRelatedProject.initAdapter(arrayOfStrings)
                            bindingView.escRelatedProject.setOnItemClickListener { parent, view, position, id ->
                                amibaProjectId = data[position].amibaProjectId
                                provideProjectName = data[position].projectName
                            }
                            super.onDataChange(data)
                        }
                    })
        }

    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == Activity.RESULT_OK) {
            when (requestCode) {
                1 -> bindingView.etDeliveryDate.setText(data?.getStringExtra("date"))
            }
        }
    }

    override fun onClick(v: View) {
        if (ClickUtil.isFastClick()) {
            return
        }
        when (v.id) {
            R.id.et_delivery_date -> IntentUtils.startActivityForResult(
                this,
                MaterialDesignCalendarActivity::class.java,
                null,
                1
            )
            R.id.superButton_submit -> {
                var escChooseUserS = ""
                if (purchaseTypeTo != "rD") {
                    escChooseUserS = bindingView.escChooseUser.editText.getText().toString().trim()
                    if (StringUtils.isEmpty(escChooseUserS)) {
                        ToastUtils.show(mContext, "请选择客户")
                        return
                    }
                }
                val escRelatedProjectS =
                    bindingView.escRelatedProject.editText.getText().toString().trim()
                if (StringUtils.isEmpty(escRelatedProjectS)) {
                    ToastUtils.show(mContext, "请选择项目")
                    return
                }
                val et_delivery_date_s =
                    bindingView.etDeliveryDate.getText().toString().trim()
                if (StringUtils.isEmpty(et_delivery_date_s)) {
                    ToastUtils.show(mContext, "请选择日期")
                    return
                }
                val metProjectOverviewS =
                    bindingView.metProjectOverview.getContentText().trim()
                if (StringUtils.isEmpty(metProjectOverviewS)) {
                    ToastUtils.show(mContext, "请填写项目概况")
                    return
                }
                val metSkillsRequirementS =
                    bindingView.metSkillsRequirement.contentText.trim()
                if (StringUtils.isEmpty(metSkillsRequirementS)) {
                    ToastUtils.show(mContext, "请填写技术要求")
                    return
                }
                updateAmibaPurchase(
                    sellPurchaseRequistionDetailBean?.amibaPurchaseId?:0,
                    customerId,
                    escChooseUserS,
                    amibaCustomerProjectId,
                    escRelatedProjectS,
                    amibaProjectId,
                    provideProjectName,
                    if (bindingView.rbModeY.isChecked()) 1 else 2,
                    et_delivery_date_s,
                    metProjectOverviewS,
                    metSkillsRequirementS
                )
                finishActivity()
            }
        }
    }

    /**
     * app端通过id查询单个详情接口
     */
    fun getAmibaPurchaseById(amibaPurchaseId: Int) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()


        amibaViewModel.getAmibaPurchaseById(amibaPurchaseId).observe(this,object : ObserverState<SellPurchaseRequistionDetailBean>(){
            override fun onDataChange(data: SellPurchaseRequistionDetailBean) {
                customDialog.dismiss()
                sellPurchaseRequistionDetailBean = data
                if (purchaseTypeTo == "market") {
                    customerId = Integer.valueOf(if (data.amibaCustomerProjectId == null) "0" else data.amibaCustomerProjectId!!)
                    bindingView.escChooseUser.setText(data.customerName)
                    amibaCustomerProjectId = Integer.valueOf(data.amibaCustomerProjectId!!)
                    bindingView.escRelatedProject.setText(data.projectName)
                } else if (purchaseTypeTo == "technology") {
                    customerId =
                        Integer.valueOf(if (data.amibaCustomerProjectId == null) "0" else data.amibaCustomerProjectId!!)
                    bindingView.escChooseUser.setText(data.customerName)
                    amibaCustomerProjectId = Integer.valueOf(data.amibaCustomerProjectId!!)
                    bindingView.escRelatedProject.setText(data.projectName)
                } else if (purchaseTypeTo == "rD") {
                    amibaProjectId = Integer.valueOf(data.amibaProjectId)
                    bindingView.escRelatedProject.setText(data.provideProjectName)
                }
                if (data.amibaPurchaseType == 1) {
                    bindingView.rbModeY.isChecked = true
                } else {
                    bindingView.rbModeN.isChecked = true
                }
                bindingView.etDeliveryDate.text = data.deliveryDate
                bindingView.metProjectOverview.contentText = data.projectOverview
                bindingView.metSkillsRequirement.contentText = data.technicalRequirement

                bindingView.escSellApprover.setText(data.approvalUser)
                bindingView.tvSellCc.text = "宁创"

                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }

        })
    }

    /**
     * app端修改销售采购申请接口
     */
    fun updateAmibaPurchase(
        amibaPurchaseId: Int,
        customerId: Int,
        customerName: String,
        amibaCustomerProjectId: Int,
        projectName: String,
        amibaProjectId: Int,
        provideProjectName: String,
        applicationMethod: Int,
        deliveryDate: String,
        projectOverview: String,
        technicalRequirement: String
    ) {
        val customDialog = CustomDialog(mContext, "正在加载...")
        customDialog.show()

        val map = mutableMapOf<String,Any>().apply {
            put("amibaPurchaseId", amibaPurchaseId)
            if (purchaseTypeTo == "market" || purchaseTypeTo == "technology") {
                put("customerId", customerId)
                put("customerName", customerName)
                put("amibaCustomerProjectId", amibaCustomerProjectId)
                put("projectName", projectName)
            } else if (purchaseTypeTo == "rD") {
                put("amibaProjectId", amibaProjectId)
                put("provideProjectName", provideProjectName)
            }
            put("applicationMethod", applicationMethod)
            put("deliveryDate", deliveryDate)
            put("projectOverview", projectOverview)
            put("technicalRequirement", technicalRequirement)
            put("updateUser", SharedPreUtils.getString("personName"))
        }

        amibaViewModel.updateAmibaPurchase(getRequestBody(map)).observe(this,object : ObserverState<BaseBean>(){
            override fun onDataChange(data: BaseBean) {
                customDialog.dismiss()
                finishActivity()
                super.onDataChange(data)
            }

            override fun onError(msg: String?, code: Int) {
                customDialog.dismiss()
                ToastUtils.showShort(mContext, msg)
                super.onError(msg, code)
            }
        })

    }
}